<template>
  <div class="coursewrap">
    <div v-if="coverFlag"
         class="cover"></div>
    <div class="course_title">
      <i class="el-icon-menu"></i>
      <div>课程信息</div>
    </div>
    <div class="base_info">
      <div class="info_left">
        <el-form label-width="100px"
                 :rules="rules"
                 :model="ruleForm"
                 ref="myform"
                 @validate="valida">
          <!-- :model 当前表单绑定的所有数据模型 
                :rules  绑定表单控件的所有规则
          -->
          <el-form-item label="课程名称:"
                        prop="Cname">
            <el-input v-model="ruleForm.Cname"></el-input>
            <span>60字以内</span>
          </el-form-item>
          <el-form-item label="课程描述："
                        prop="Cdescribe">
            <el-input v-model="ruleForm.Cdescribe"></el-input>
            <span>100字以内</span>
          </el-form-item>
          <el-form-item label="课程价格："
                        prop="Cprice">
            <el-input v-model="ruleForm.Cprice"></el-input>
            <span>课程价格以元为单位，免费课程设置为0</span>
          </el-form-item>
          <el-form-item label="专业选择："
                        class="sel">
            <el-select v-model="ruleForm.CategoryOne"
                       prop="CategoryOne">
              <el-option v-for="item in opt1"
                         :key="item.label"
                         :value="item.value"
                         :label="item.label"></el-option>
            </el-select>
            <el-select v-model="ruleForm.CategoryTwo"
                       prop="CategoryTwo">
              <el-option v-for="item in opt2"
                         :key="item.label"
                         :value="item.value"
                         :label="item.label"></el-option>
            </el-select>
            <el-select v-model="ruleForm.CategoryThree"
                       prop="CategoryThree">
              <el-option v-for="item in opt3"
                         :key="item.label"
                         :value="item.value"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success"
                       @click="saveCourse"
                       v-if="!$route.query.action">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="info_right">
        <div class="img_title">
          课程封面：
        </div>
        <div class="img_wrap">
          <img :src="upImgUrl"
               alt="">
        </div>
        <div class="img_ctrl">
          <el-link @click="clearImg()"
                   type="danger">清除</el-link>
          <el-link type="success"
                   @click="diaFlag=true">上传</el-link>
        </div>
      </div>
    </div>
    <!-- /DownLoadPicHandler?pathName=EUWR4762pic -->
    <el-dialog title="课程封面选择："
               :visible.sync="diaFlag">
      <div v-show="imgFlag">
        <!-- 隐藏的文件上传框 -->
        <input type="file"
               hidden
               accept="image/*"
               ref="myfile"
               @change="imgChange">
        <el-input disabled></el-input>
        <el-button @click="selectImg"
                   type="success">选择文件</el-button>
      </div>
      <div v-show="!imgFlag"
           class="sureImg">
        <img :src="urlImg"
             alt="">
        <span slot="footer">
          <el-button type="success"
                     @click="uploadImg">确定</el-button>
          <el-button type="primary"
                     @click="cancelUp">取消</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { upImgApi, addCourse, getCourseById } from '../../api/course'
export default {
  name: 'Ljfvue2011Coursebase',
  data () {
    return {
      dirlist: [],//目录列表
      CDid: "",//课程id
      coverFlag: false,
      upImgUrl: "",//课程缩略图
      urlImg: "",//确认缩略图地址
      imgFlag: true,
      diaFlag: false, //上传框
      ruleForm: { //课程基本信息
        Cname: "",		//课程名称	
        Cdescribe: "",	//课程描述	
        Cprice: "",		//价格	
        CategoryOne: "", //一级分类	
        CategoryTwo: "",//		二级分类	
        CategoryThree: "",//		三级分类	
        Cpic: "", //封面图src地址
      },
      rules: { //表单验证规则
        Cname: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // pattern 加载正则验证
        Cdescribe: { pattern: /^[\u4E00-\u9FA5]+$/, required: true, message: "必填和必须输入中文", trigger: 'blur' },
        //  type: 'email' number date  array
        Cprice: { pattern: /^\d{1,4}$/, message: '课程价格必须为数字值和不能太过分', trigger: ['blur'] }
      },
      opt1: [{
        value: "1",
        label: "前端"
      }, {
        value: "2",
        label: "后台"
      }, {
        value: "3",
        label: "视觉设计"
      }],
      opt2: [{
        value: "11",
        label: "JS"
      }, {
        value: "12",
        label: "Vue"
      }, {
        value: '13',
        label: "Webpack"
      },
      {
        value: "21",
        label: "Java"
      },
      {
        value: "22",
        label: "PHP"
      },
      {
        value: "22",
        label: "python"
      },
      {
        value: "31",
        label: "PS"
      },
      {
        value: "32",
        label: "蓝湖"
      },
      {
        value: "33",
        label: "Vi"
      }],
      opt3: [
        { value: "111", label: "js基础" },
        { value: "112", label: "js高级" }
      ],
      valiobj: { //各个表单元素的验证结果
        Cname: false,
        Cdescribe: false,
        Cprice: false
      }
    };
  },

  mounted () {

  },
  watch: {
    ruleForm: {
      handler (newVal) {
        // 子组件数据发生变化 传递给父组件
        this.$emit("sendform", newVal)
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    // 假如有课程id 请求课程信息
    if (this.$route.query.CDid) {
      getCourseById(this.$route.query.CDid).then(res => {
        console.log(res)
        console.log(9999999)
        var infoData = res.data.data.courselist;
        this.ruleForm.Cname = infoData.Cname;
        this.ruleForm.Cprice = infoData.Cprice;
        this.ruleForm.Cdescribe = infoData.Cdescribe;
        this.ruleForm.CategoryOne = infoData.CategoryOne;
        this.ruleForm.CategoryTwo = infoData.CategoryTwo;
        this.ruleForm.CategoryThree = infoData.CategoryThree;
        console.log(infoData.Cpic)
        this.upImgUrl = "http://localhost:3000" + infoData.Cpic;
        if (!this.$route.query.action) { //不是修改的 而且有课程id请求
          this.coverFlag = true;
        }
        this.$parent.dirCoverFlag = false;
        this.$emit("senddeta", infoData.Cdetails)
        // 存储目录列表
        this.dirlist = res.data.data.dirlist;
        // 传送目录信息 给兄弟组件
        this.$bus.$emit("senddir", this.dirlist)
      })
    }
  },
  methods: {
    clearImg () { //清除封面
      this.urlImg = "";
      this.upImgUrl = "";
      this.$refs.myfile.value = ""
    },
    valida (prop, flag) { //所有表单的验证
      console.log(12313)
      console.log(prop, flag) //Cname false
      this.$set(this.valiobj, prop, flag)
      console.log(this.$data); //当前组件的所有数据
    },
    async saveCourse () { //课程添加
      if (this.ruleForm.Cpic && this.valiobj.Cname && this.valiobj.Cprice && this.valiobj.Cdescribe) {
        var res = await addCourse(this.ruleForm);
        this.$message({
          message: "上传课程成功",
          type: "success"
        })
        // 清空选择的图片
        this.$refs.myfile.value = ""
        // 存储课程id 
        this.CDid = res.data.ID;
        // 添加完课程  显示遮罩
        this.coverFlag = true;
        this.$parent.dirCoverFlag = false;
        // 清空整个表单
        // this.$refs.myform.resetFields()
        this.ruleForm.Cpic = "";
        console.log(this.ruleForm)
        // this.upImgUrl = "";//清除缩略图
        this.$router.push({ name: "courseadd", query: { _cid: res.data._id, CDid: res.data.ID, upImgUrl: this.upImgUrl } })
      } else {
        this.$message.error("输入的信息不符合规则或图片封面未上传")
      }
    },
    selectImg () { //点击按钮弹出文件上传选择
      this.$refs.myfile.click();
    },
    imgChange () { //选择了图片
      this.imgFlag = false;//切换布局
      // 制作缩略图方法 object 文件内容
      var files = this.$refs.myfile.files[0]; //文件内容
      this.urlImg = URL.createObjectURL(files);
      console.log(this.urlImg) //缩略图路径
    },
    cancelUp () { //取消上传
      this.diaFlag = false;
      this.imgFlag = true;
    },
    async uploadImg () { //上传图片接口
      var formdata = new FormData();
      //   FormData.append(key,上传的文件内容)
      var files = this.$refs.myfile.files[0];
      formdata.append(new Date().getTime().toString(), files)
      // data 图片数据包
      var res = await upImgApi(formdata)
      console.log(res);
      this.diaFlag = false;//关闭弹出层
      this.imgFlag = true;//重置图片选择
      this.upImgUrl = this.urlImg;//课程封面显示
      this.$refs.myfile.value = ""
      // 存储后台返回的上传成功后的地址
      this.ruleForm.Cpic = res.data.cacheName;
    }
  },
};
</script>

<style lang="less" >
.course_title {
  width: 100%;
  display: flex;
  height: 40px;
  margin: 20px 0;
  line-height: 40px;
  i {
    height: 40px;
    font-size: 40px;
    width: 40px;
    border: 2px solid red;
  }
  div {
    padding-left: 40px;
    height: 44px;
    flex: 1;
    box-sizing: border-box;
    border-top: 2px solid red;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
  }
}
.base_info {
  width: 100%;
  height: 360px;
  box-shadow: 5px 5px 5px black;
  display: flex;
  .info_left {
    padding: 40px 0;
    box-sizing: border-box;
    width: 65%;
    height: 360px;
    background: black;
    .el-form-item__label {
      color: white;
    }
    .el-input {
      width: 300px;
    }
  }
  .info_right {
    background: black;
    flex: 1;
    height: 360px;
    // background: darksalmon;
    padding: 40px 20px;
    box-sizing: border-box;
    .img_title {
      width: 250px;
      line-height: 40px;
      font-size: 20px;
      color: white;
    }
    .img_wrap {
      width: 250px;
      height: 180px;
      border: 2px solid red;
      img {
        width: 250px;
        height: 180px;
      }
    }
    .img_ctrl {
      width: 250px;
      display: flex;
      justify-content: space-between;
      .el-link {
        font-size: 20px;
      }
    }
  }
}
.el-form-item {
  span {
    color: white;
    margin-left: 40px;
  }
  .el-button {
    span {
      margin-left: 0;
    }
  }
}
.sel {
  .el-select {
    width: 140px;
    margin-right: 30px;
    .el-input {
      width: 140px;
    }
  }
}
.sureImg {
  img {
    width: 300px;
    height: 300px;
    margin-right: 40px;
  }
}
.coursewrap {
  position: relative;
}
.cover {
  width: 100%;
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
  height: 430px;
  left: 0;
  z-index: 999;
  top: 0;
}
</style>